﻿#include "CQue.h"
#include <string.h>

int cque_push(CQue* thes, void* v) {
	CList* l = &thes->list;
	if (thes->is_with_lock) {
//		thes->lock.wait(&thes->lock);
	}

	l->insert(l, (void*)&v);

	if (thes->is_with_lock) {
//		thes->lock.signal(&thes->lock);
	}
	return 0;
}

void* cque_pop(CQue* thes) {
	void* ret = 0;
	CList* l = &thes->list;
	CListIterator it;
	construct_clist_iterator(&it);

	if (0 >= l->cnt) {
		return 0;
	}
	it.ptr = l->begin(l);
	ret = *IT_PTR(it, void*);
	l->erase(l, &it);
	return ret;
}

int cque_release(CQue* thes) {
	thes->list.release(&thes->list);
	return 0;
}

void construct_queue(CQue* thes, int with_lock) {
	construct_clist(&thes->list, sizeof(void*));
	thes->is_with_lock = with_lock;
	if (with_lock) {
//		construct_sem(&thes->lock, 1);
	} else {
//		memset(&thes->lock, 0, sizeof(thes->lock));
	}

	thes->push = cque_push;
	thes->pop = cque_pop;
	thes->release = cque_release;
}

//
//int cque_push(CQue* thes, void* v) {
//	if (thes->is_with_lock) {
//		thes->lock.wait(&thes->lock);
//	}
//
//	if (thes->write_pos >= MAX_Q_ITEM_CNT) {
//		thes->write_pos = 0;
//	}
//
//	if (thes->cnt >= MAX_Q_ITEM_CNT) {
//		return -1;
//	}
//
//	thes->q[thes->write_pos] = v;
//	++thes->write_pos;
//	++thes->cnt;
//
//	if (thes->is_with_lock) {
//		thes->lock.signal(&thes->lock);
//	}
//	return 0;
//}
//
//void* cque_pop(CQue* thes) {
//	void* ret = 0;
//
//	if (0 >= thes->cnt) {
//		return 0;
//	}
//
//	if (thes->read_pos >= MAX_Q_ITEM_CNT) {
//		thes->read_pos = 0;
//	}
//
//	ret = thes->q[thes->read_pos];
//	--thes->cnt;
//	++thes->read_pos;
//	return ret;
//}
//
//void construct_queue(CQue* thes, int with_lock) {
//	thes->cnt = 0;
//	thes->read_pos = 0;
//	thes->write_pos = 0;
//	memset(thes->q, 0, sizeof(thes->q));
//	thes->is_with_lock = with_lock;
//	if (with_lock) {
//		construct_sem(&thes->lock, 1);
//	} else {
//		memset(&thes->lock, 0, sizeof(thes->lock));
//	}
//
//	thes->cque_push = cque_push;
//	thes->cque_pop = cque_pop;
//}
